import { getOpenId, loginByOpenId, getUserPerms, userLogout, isCustomizationCustomer } from '@/network/apis';
import WebSocket from '@/network/websocket.js';
import Taro from '@tarojs/taro';
import { router, storage, toast } from '@/utils';

export const USER_TYPE_MAP = {
	2: 'manufacturer',
	3: 'company'
};

export const getCode = () => {
	return new Promise((resolve, reject) => {
		Taro.login({
			provider: 'weixin',
			success: function (loginRes) {
				resolve(loginRes.code);
			},
			fail: function (c) {
				reject(c);
			}
		});
	});
};

export const getWxOpenId = () => {
	return new Promise(async (resolve, reject) => {
		const wxCode = await getCode();
		const { openid } = await getOpenId({ code: wxCode });

		if (openid) {
			storage.set('openId', openid);
			resolve(openid);
		} else {
			toast.showToast({ title: '获取OpenId失败', icon: 'error' });
		}
	});
};

export const userAutoLogin = (loginParam = {}) => {
	return new Promise(async (resolve, reject) => {
		const openId = storage.get('openId') || (await getWxOpenId());
		const loginType = 2; // 微信小程序
		const cType = 0; // 所有制造商

		const { mobile, customerId, scanBaseId } = loginParam;

		const requestParams = {
			openId: openId,
			type: cType,
			mobile: storage.get('mobile') || mobile || '',
			customerId: storage.get('cid') || customerId || '',
			loginType: loginType
		};

		const { ret, data, message } = await loginByOpenId(requestParams);

		if (ret !== 0) {
			toast.showToast({ title: `登录失败，${message || '未知错误'}`, icon: 'none' });

			setTimeout(() => {
				logout();
			}, 1000);
		}

		afterLogin({ ...data, scanBaseId });

		return resolve();
	});
};

export const checkCustomization = async () => {
	const { data } = await isCustomizationCustomer({ companyId: storage.get('manufacturerId') });
	storage.set('isCustomization', data?.isCustomization || 0);
};

export const afterLogin = async data => {
	login(data);
	// await checkCustomization();

	switch (data.companyType) {
		case 3: // 使用商
			// 消息订阅
			addSubscribeWhenCompany(data);
			break;
		case 2: // 制造商
			await getMenuDroit();

			// 消息订阅
			addSubscribeWhenManufacturer(data);
			break;
		default:
			Taro.showToast({ duration: 5000, title: '身份识别失败', icon: 'error' });
			break;
	}

	const jumpUrl = data?.scanBaseId ? `/pages/index/index?scanBaseId=${data?.scanBaseId}` : '/pages/index/index';

	setTimeout(() => {
		router.reLaunch({ url: jumpUrl });
	}, 1000);
};

export const login = data => {
	console.log('login', data);
	data?.isCustomization && storage.set('isCustomization', data.isCustomization || 0);
	storage.set('token', data.token);
	storage.set('name', data.userName);
	storage.set('head', data.wxAvatar || data.ddAvatar || 'https://platform-icon.oss-cn-hangzhou.aliyuncs.com/default-avatar.png');
	storage.set('userid', data.uid);
	storage.set('cid', data.cid);
	storage.set('manufacturerId', data.manufacturerId);
	storage.set('manufacturerName', data.manufacturerName);
	storage.set('companyName', data.companyName);
	storage.set('address', data.address);
	storage.set('mobile', data.mobile);
	storage.set('deptId', data.deptId);
	storage.set('type', USER_TYPE_MAP[data.companyType]);
	storage.set('isCustomization', data?.isCustomization || 0);
};

export const logout = async (reLogin = true) => {
	await userLogout(2); // 2 微信 3：钉钉

	storage.remove('token');
	storage.remove('name');
	storage.remove('head');
	storage.remove('userid');
	storage.remove('cid');
	storage.remove('manufacturerId');
	storage.remove('manufacturerName');
	storage.remove('companyName');
	storage.remove('address');
	storage.remove('mobile');
	storage.remove('deptId');
	storage.remove('type');

	reLogin && router.reLaunch({ url: '/pages/login' });

	return Promise.resolve();
};

export const logoutLocal = () => {
	// 清空本地数据
	storage.clear();
	router.reLaunch({ url: '/pages/login' });
};

// 使用商时候需要发起的订阅
export const addSubscribeWhenCompany = data => {
	// 订阅权限的变化（使用商）
	WebSocket.addSubscribeAuthChange('/topic/auth-change/' + data.uid);
	// 订阅公司被拉黑
	WebSocket.addSubscribeBlack('/topic/black/' + data.cid);
	// 订阅账号被拉黑
	WebSocket.addSubscribeBlack('/topic/blackstaff/' + data.uid);
	// 订阅问题列表需要刷新
	WebSocket.addSubscribeProblemChange('/topic/problemchange/' + data.manufacturerId);
};

// 制造商时候需要发起的订阅
export const addSubscribeWhenManufacturer = data => {
	// 订阅权限的变化（制造商）
	WebSocket.addSubscribeAuthChange('/topic/auth-change/' + data.uid);
	// 订阅账号被拉黑
	WebSocket.addSubscribeBlack('/topic/blackstaff/' + data.uid);
	// 订阅问题列表需要刷新
	WebSocket.addSubscribeProblemChange('/topic/problemchange/' + data.cid);
	// 订阅我的界面的刷新
	WebSocket.addSubscribeMyPageChange('/topic/mypagechange/' + data.uid);
};

export const getMenuDroit = () => {
	return new Promise(async (resolve, reject) => {
		// if (Taro.getStorageSync("droitIdList")) {
		//   return resolve();
		// }

		const { ret, data } = await getUserPerms();

		if (ret !== 0) resolve();

		let idList = [],
			permList = data?.length ? data : [];

		// 递归函数，取出permList中所有的id
		const getDroitIdList = list => {
			list.forEach(e => {
				e.id && idList.push(e.id);

				if (e.childMenus && e.childMenus.length > 0) {
					getDroitIdList(e.childMenus);
				}
			});
		};

		getDroitIdList(permList);

		storage.set('droitIdList', JSON.stringify(idList));

		return resolve();
	});
};
